package com.youboy.wechatapi.utils.db;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;



public class BaseDBCon {
	// DataSource是DBCP的数据库连接
	private static DataSource kwfilterDs = null;
	private static DataSource industryDs = null;
	private static DataSource performanceSource = null;
	// 返回数据库连接
	public static Connection getConnection(String dbtype) throws SQLException {
		// 从DataSource中获取一个空闲得连接并返回给调用它的方法94_mongodbFile-config.xml
		DataSource ds = null;
		try {
			if (dbtype.equals("kwfilter_db")) { // 词库
				ds = kwfilterDs == null ? kwfilterDs = initDataSource("kwfilter_db")
						: kwfilterDs;
			} else if (dbtype.equals("industry_db")) { // 行业分类
				ds = industryDs == null ? industryDs = initDataSource("industry_db")
						: industryDs;
			} else if (dbtype.equals("performance_source_db")) {
				ds = performanceSource == null ?performanceSource = initDataSource("performance_source_db")
						: performanceSource;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return ds.getConnection();
	}

	@SuppressWarnings("static-access")
	private static DataSource initDataSource(String dbtype) throws Exception {
		DataSource ds = null;
		Properties prop = new Properties();
		// BaseDBCon.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
		InputStream is = new FileInputStream((new StringBuilder(
				String.valueOf(BaseDBCon.getClassPath()))).append(
				dbtype + ".properties").toString());
		prop.load(is);

		// DBCP的连接池工厂
		BasicDataSourceFactory factory = new BasicDataSourceFactory();
		// 通过这个工厂，我们获得一个根据资源文件配置的数据库连接池
		ds = factory.createDataSource(prop);
		return ds;
	}
	
	public static String getClassPath() {
		boolean isWindows = System.getProperty("os.name").toLowerCase()
				.startsWith("windows");
		BaseDBCon o = new BaseDBCon();
		String strPackageName = "";
		if (o.getClass().getPackage() != null)
			strPackageName = o.getClass().getPackage().getName();
		String strClassName = o.getClass().getName();
		String strClassFileName;
		if (!strPackageName.equals(""))
			strClassFileName = strClassName.substring(
					strPackageName.length() + 1, strClassName.length());
		else
			strClassFileName = strClassName;
		URL url = o.getClass().getResource(
				(new StringBuilder(String.valueOf(strClassFileName))).append(
						".class").toString());
		String strURL = url.toString();
		try {
			strURL = URLDecoder.decode(strURL, "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
		strURL = strURL.substring(strURL.indexOf('/') + (isWindows ? 1 : 0),
				strURL.lastIndexOf('/') - strPackageName.length());
		return strURL;
	}
}
